package com.lzy.algorithm;

/**
 * Author: lzy
 * Date:   2020/06/19 14:13
 * Description:
 **/
public class 二分查找 {


    public static void main(String[] args) {
        int[] nums = new int[]{1, 4, 6, 8, 9, 34, 56};
        int left = 0;
        int right = nums.length;
        // int index = getNumFromArray(nums, -8);
        int index = getNumFromArrayDG(nums, left, right, -6);
        System.out.println(index);
    }

    public static int getNumFromArray(int[] nums, int target) {

        int left = 0;
        int right = nums.length;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    public static int getNumFromArrayDG(int[] nums, int left, int right, int target) {
        if(left > right){
            return -1;
        }
        int mid = (left + right) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            return getNumFromArrayDG(nums, mid + 1, right, target);
        } else {
            return getNumFromArrayDG(nums, left, mid - 1, target);
        }
    }
}
